#!/usr/bin/env python3
# config.py

import json
import logging
import argparse
from pathlib import Path
from typing import Optional


CONFIG_FILE = Path("~/.demucs_gui_config.json").expanduser()

logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s")


class Config:
    def __init__(self, config_path: Path = Path(CONFIG_FILE), cli_args: Optional[argparse.Namespace] = None):
        self.config_path = config_path
        self.last_file: Optional[str] = None
        self.output_format: str = "wav"
        self.load()

        if cli_args:
            if cli_args.input_file:
                self.last_file = cli_args.input_file
            if cli_args.format:
                self.output_format = cli_args.format
        self.save()
        # QMessageBox 不能在无窗口上下文调用时弹出，放在 GUI 初始化后

    def load(self):
        try:
            if self.config_path.exists():
                with open(self.config_path) as f:
                    data = json.load(f)
                    logging.info(f"raw data:{data}")
                    self.last_file = data.get("last_file")
                    self.output_format = data.get("output_format", "wav")
        except Exception as e:
            logging.warning(f"Failed to load config: {e}")

    def save(self):
        try:
            with open(self.config_path, "w") as f:
                json.dump({
                    "last_file": self.last_file,
                    "output_format": self.output_format
                }, f)
        except Exception as e:
            logging.warning(f"Failed to save config: {e}")
